<template>
	<modeBoxTemplate>
		<el-form :model="formData" :rules="rules" ref="ruleFormRef" label-position="top" hide-required-asterisk>
			<el-form-item prop="target" label="需要替换的路径">
				<el-input
					v-model="formData.target"
					placeholder="需要替换的路径"
					ref="targetInput"
					@keyup.enter="onEnter" />
			</el-form-item>
			<el-form-item prop="substituted" label="替换的路径">
				<el-input
					v-model="formData.substituted"
					placeholder="替换的路径"
					ref="substitutedInput"
					@keyup.enter="onEnter" />
			</el-form-item>
		</el-form>
		<el-button type="primary" :disabled="workOngoing" @click="query">查询</el-button>
	</modeBoxTemplate>
</template>

<script setup lang="ts">
import { API } from '@v/utils/API';
import { reactive, ref } from 'vue';
import { rootMixin } from '@v/mixin';
import { useRootStore } from '@v/store';
import { ElNotification } from 'element-plus';
import type { FormInstance } from 'element-plus';
import { useMode2Store } from '@v/store/mode/mode2';
import modeBoxTemplate from '../modeBoxTemplate.vue';
import _ from 'lodash';
import { QueryReplaceInfo } from '@type/replace';

const { workOngoing } = rootMixin();

const store = useRootStore();
const mode2Store = useMode2Store();

const formData = reactive({
	target: '',
	substituted: '',
});

const rules = {
	target: [{ required: true, message: '不能为空', trigger: 'blur' }],
};

const ruleFormRef = ref<FormInstance>();
const targetInput = ref();
const substitutedInput = ref();

// 回车事件
function onEnter() {
	if (!formData.target) {
		targetInput.value.focus();
	} else if (!formData.substituted) {
		substitutedInput.value.focus();
	} else {
		query();
	}
}

// 查询
function query() {
	if (!ruleFormRef.value) return;

	ruleFormRef.value.validate((valid) => {
		if (!valid) return;

		if (formData.target === formData.substituted) {
			return ElNotification({
				title: '提示',
				message: '"需要替换的路径" 和 "替换的路径" 不能一样',
				type: 'warning',
				position: 'top-left',
			});
		}

		API.invoke('query-images-reference-path-replace-info', [_.cloneDeep(formData)]).then(
			(arr: QueryReplaceInfo[]) => {
				if (arr.length > 0) {
					mode2Store.setReplaceInfo(arr);
					mode2Store.setData(_.cloneDeep(formData));
					store.setDrawer_isShow(true);
				} else {
					ElNotification({
						title: '提示',
						message: '未在文档中匹配到结果',
						type: 'warning',
						position: 'top-left',
					});

					if (store.drawer_isShow) {
						mode2Store.setReplaceInfo(arr);
						mode2Store.setData(_.cloneDeep(formData));
					}
				}
			}
		);
	});
}
</script>
